package com.lmx.persistence.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import com.lmx.common.constants.CommonConstants;
import com.lmx.common.constants.ICommonConstants;
import com.lmx.common.context.ActionContextHolder;
import com.lmx.common.util.CommonUtil;
import com.lmx.repoDomain.tmodel.Bed;
import com.lmx.repoDomain.tmodel.Call;
import com.lmx.repoDomain.tmodel.Customer;
import com.lmx.repoDomain.tmodel.DealFlow;
import com.lmx.repoDomain.tmodel.Dicttype;
import com.lmx.repoDomain.tmodel.HbeaconWarning;
import com.lmx.repoDomain.tmodel.Message;
import com.lmx.repoDomain.tmodel.PayRecord;
import com.lmx.repoDomain.tmodel.PersonLocation;
import com.lmx.repoDomain.tmodel.Task;
import com.lmx.repoDomain.tmodel.Tenant;
import com.lmx.repoDomain.tmodel.UserSession;
import com.lmx.repoDomain.tmodel.UserTask;
import com.lmx.repoDomain.tmodel.Wechat;
import com.lmx.repoDomain.tmodel.Workorder;
//import com.lmx.repoDomain.model.*;
import com.lmx.repoDomain.tmodel.business.User;//huibati

/**
 * 消息处理类
 */
@Service
public class MessageService {
	private Log logger = LogFactory.getLog(this.getClass());

	@PersistenceContext
	private EntityManager em;

	@Autowired
	private GenericService dslJpaService;

	@Autowired
	private CommonService commonService;

	@Autowired
	private UserService userService;

	@Autowired
	private WorkPlaceService workPlaceService;

	@Resource(name = "jdbcTemplate")
	private JdbcTemplate jdbcTemplate;

	protected JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	/**
	 * 发送消息
	 */
	public void sendMessage(Message message, Long userId) {
		// 获取对应 WebSocketSession
		String uid = userId.toString();
		if (ActionContextHolder.getUidSocketSessionHolder().get(uid) == null
				|| ActionContextHolder.getUidSocketSessionHolder().get(uid)
						.size() == 0) {
			logger.debug("签到：未能获取有效token   uid：" + uid);
			return;
		}
		for (WebSocketSession session : ActionContextHolder
				.getUidSocketSessionHolder().get(uid)) {
			if (session == null) {
				logger.debug("签到：未能获取WebSocketSession   uid：" + uid);
				return;
			}
			// 配置json转换过滤规则
			JsonConfig config = new JsonConfig();
			config.setJsonPropertyFilter(new PropertyFilter() {
				@Override
				public boolean apply(Object source, String name, Object value) {
					if (name.equals("toUser") || name.equals("fromUser")
							|| name.equals("userList") || name.equals("tenant")) {
						return true;
					} else {
						return false;
					}
				}
			});
			JSONObject jsonObject = JSONObject.fromObject(message, config);
			JSONObject fromUserJson = new JSONObject();
			if (message.getFromUser() != null) {
				fromUserJson
						.put("id", message.getFromUser().getId().toString());
				fromUserJson.put("name", message.getFromUser().getName()
						.toString());
			}
			jsonObject.put("fromUser", fromUserJson.toString());
			// jsonObject.put("toUser",JSONObject.fromObject(message.getToUser().toString()));
			String jsonContent = jsonObject.toString();
			logger.debug("webSocket 发送消息：" + jsonContent);
			try {
				session.sendMessage(new TextMessage(jsonContent));
			} catch (Exception e) {
				logger.debug("webSocket发送信息失败：" + e.toString());
			}
		}
	}

	/**
	 * 发送消息
	 */
	public void sendMessage(Message message) {
		// 获取对应 WebSocketSession
		String uid = message.getToUser().getId().toString();
		if (ActionContextHolder.getUidSocketSessionHolder().get(uid) == null
				|| ActionContextHolder.getUidSocketSessionHolder().get(uid)
						.size() == 0) {
			logger.debug("签到：未能获取有效token   uid：" + uid);
			return;
		}
		for (WebSocketSession session : ActionContextHolder
				.getUidSocketSessionHolder().get(uid)) {
			if (session == null) {
				logger.debug("签到：未能获取WebSocketSession   uid：" + uid);
				return;
			}
			// 配置json转换过滤规则
			JsonConfig config = new JsonConfig();
			config.setJsonPropertyFilter(new PropertyFilter() {
				@Override
				public boolean apply(Object source, String name, Object value) {
					if (name.equals("toUser") || name.equals("fromUser")
							|| name.equals("userList") || name.equals("tenant")) {
						return true;
					} else {
						return false;
					}
				}
			});
			JSONObject jsonObject = JSONObject.fromObject(message, config);
			JSONObject fromUserJson = new JSONObject();
			if (message.getFromUser() != null) {
				fromUserJson
						.put("id", message.getFromUser().getId().toString());
				fromUserJson.put("name", message.getFromUser().getName()
						.toString());
			}
			jsonObject.put("fromUser", fromUserJson.toString());
			// jsonObject.put("toUser",JSONObject.fromObject(message.getToUser().toString()));
			String jsonContent = jsonObject.toString();
			logger.debug("webSocket 发送消息：" + jsonContent);
			try {
				session.sendMessage(new TextMessage(jsonContent));
			} catch (Exception e) {
				logger.debug("webSocket发送信息失败：" + e.toString());
			}
		}
	}

	/**
	 * 判断并发送签到提醒
	 */
	public void signRemind() {
		logger.debug("开始签到提醒");
		// ArrayList<WebSocketSession> sessions = new
		// ArrayList<WebSocketSession>();
		ArrayList<Long> userTaskIds = (ArrayList<Long>) this.em
				.createQuery(
						"select distinct a.userTask.id from ApplyWorktime a where a.runStatus = ?1")
				.setParameter(1,
						(short) ICommonConstants.RUNSTATUS.HASBEGUN.ordinal())
				.getResultList();

		/*
		 * userTaskIds.add(-1L); //debugTest ArrayList<Long> uids =
		 * (ArrayList<Long>)this.em.createQuery(
		 * "select distinct u.user.id from UserTask u where u.id in ?1")
		 * .setParameter(1,userTaskIds) .getResultList();
		 */

		for (int i = 0; i < userTaskIds.size(); i++) {
			UserTask userTask = this.em
					.find(UserTask.class, userTaskIds.get(i));
			String uid = userTask.getUser().getId().toString();

			Message message = new Message();
			message.setFromUser(commonService.getSystemUser());// 系统用户
			message.setType((short) ICommonConstants.MESSAGETYPE.REMIND
					.ordinal());
			message.setDetailType((short) ICommonConstants.REMINDDETAILTYPE.SIGN
					.ordinal());
			message.setToUser(this.em.find(User.class, userTask.getUser()
					.getId()));
			message.setCode("1207");
			message.setBusiness("sign");
			message.setHasRead((short) 0);
			// 设置content debugTest
			Map<String, String> msgMap = new HashMap<String, String>();
			msgMap.put("userTaskId", userTask.getId().toString());
			msgMap.put("taskId", userTask.getTask().getId().toString());
			msgMap.put("taskTitle", userTask.getTask().getTitle());
			message.setContent(CommonUtil.mapToJsonString(msgMap));
			dslJpaService.setEntityClass(Message.class);
			message = (Message) dslJpaService.create(message);

			sendMessage(message);
			logger.debug("签到提醒结束");
		}

	}

	/**
	 * 保存WebSocketSession
	 */
	public void saveSession(String message, WebSocketSession session) {
		int start = message.indexOf("{");
		int end = message.indexOf("}");
		String jsonStr = "";
		if (start > -1 && end > -1) {
			jsonStr = StringUtils.substring(message, start, end + 1);
			JSONObject jsonObject = JSONObject.fromObject(jsonStr);
			String code = jsonObject.get("code").toString(); // 获取协议号
			logger.debug("websocket code ：" + code);
			if (StringUtils.isBlank(code) || !"01".equals(code)) {
				logger.debug("webSocketSession未保存");
				return;
			}
			logger.debug("websocket:" + jsonObject.toString());
			String token = (String) jsonObject.get("token");
			ActionContextHolder.getEvaHolder().get(token)
					.setWebSocketSession(session);
			// test socket
			if (ActionContextHolder.getEvaHolder().get(token).getId() != null) {
				if (ActionContextHolder.getUidSocketSessionHolder().get(
						ActionContextHolder.getEvaHolder().get(token).getId()
								.toString()) == null) {
					List<WebSocketSession> sessions = new ArrayList<>();
					sessions.add(session);
					ActionContextHolder.getUidSocketSessionHolder().put(
							ActionContextHolder.getEvaHolder().get(token)
									.getId().toString(), sessions);
				} else {
					ActionContextHolder
							.getUidSocketSessionHolder()
							.get(ActionContextHolder.getEvaHolder().get(token)
									.getId().toString()).add(session);
				}
			}
			logger.debug("保存webSocketSession,token=" + token + ":::::userId :　"
					+ ActionContextHolder.getEvaHolder().get(token).getId());
		}
	}

	/**
	 * 发送任务提醒
	 *
	 * @param userTask
	 */
	public void taskRemind(UserTask userTask, String type) {
		logger.debug("进入任务提醒方法:" + type);
		long taskId = userTask.getTask().getId();
		Task task = this.em.find(Task.class, taskId);

		String code = "1201"; // 协议号
		String business = ""; // 业务编码
		Short detailType = (short) ICommonConstants.REMINDDETAILTYPE.TASKREMIND
				.ordinal();
		; // 提醒详细类型
		User user = new User();
		if (type.equals("taskApply")) {
			logger.debug("任务已申请通知");
			business = "taskApply";
			user = this.em.find(User.class, task.getPubuser().getId());
		} else if (type.equals("taskApplySucc")) {
			logger.debug("任务申请已通过通知");
			business = "taskApplySucc";
			user = this.em.find(User.class, userTask.getUser().getId());
		} else if (type.equals("taskApplyFail")) {
			logger.debug("任务申请企业审核未通过通知");
			business = "taskApplyFail";
			user = this.em.find(User.class, userTask.getUser().getId());
		} else if (type.equals("taskApplySuccNotLocateSeat")) {
			logger.debug("任务申请已通过(未分配座席)通知");// debugTest 通知运营
			business = "taskApplySuccNotLocateSeat";
			user = this.em.find(User.class, userTask.getUser().getId());
			String content = "客服loginName" + user.getLoginName() + "<br>客服名称："
					+ user.getName() + "<br>企业名称："
					+ task.getPubuser().getEntName() + "<br>任务名称："
					+ task.getTitle() + "<br>申请时间："
					+ CommonUtil.getCurrTimeForString();
			commonService.operateRemind("客服通过企业任务审核(邀请) 分配坐席", content);
		} else if (type.equals("taskApplyInvited")) {
			logger.debug("任务已邀请通知");
			business = "taskApplyInvited";
			user = this.em.find(User.class, userTask.getUser().getId());
		} else if (type.equals("taskApplyRefuseInvitation")) {
			logger.debug("任务已拒绝邀请通知");
			business = "taskApplyRefuseInvitation";
			user = this.em.find(User.class, task.getPubuser().getId());
		} else {
			logger.debug("call 事件失效通知，type：" + type);
		}

		Message message = new Message();
		message.setFromUser(commonService.getSystemUser());// 系统
		message.setType((short) ICommonConstants.MESSAGETYPE.REMIND.ordinal());
		message.setDetailType(detailType);
		message.setToUser(user);
		message.setCode(code);
		message.setBusiness(business);
		message.setHasRead((short) 0);
		// 设置content debugTest
		Map<String, String> msgMap = new HashMap<String, String>();
		msgMap.put("userTaskId", userTask.getId().toString());
		msgMap.put("userId", userTask.getUser().getId().toString());
		msgMap.put("taskId", Long.toString(taskId));
		msgMap.put("taskTitle", task.getTitle());
		msgMap.put("userTaskStatus", userTask.getStatus().getTypecode());
		message.setContent(CommonUtil.mapToJsonString(msgMap));
		dslJpaService.setEntityClass(Message.class);
		message = (Message) dslJpaService.create(message);
		sendMessage(message);
		logger.debug("开始发送任务提醒:" + type);

	}

	/**
	 * 电话事件提醒
	 */
	public void callRemind(Call call, String type) {
		logger.debug("电话事件通知开始");
		Task task = this.em.find(Task.class, call.getTask().getId());
		User agent = call.getAgent();
		String code = ""; // 协议号
		String business = ""; // 业务编码
		Short detailType = null; // 电话事件详细类型
		if (type.equals("callWait")) {
			logger.debug("等待接听事件通知");
			code = "1301";
			business = "callWait";
			detailType = (short) ICommonConstants.CALLDETAILTYPE.CALLDIALING
					.ordinal();
		} else if (type.equals("callInBusy")) {
			logger.debug("通话中事件通知");
			code = "1302";
			business = "callInBusy";
			detailType = (short) ICommonConstants.CALLDETAILTYPE.CALLINBUSY
					.ordinal();
		} else if (type.equals("callEnd")) {
			logger.debug("通话结束事件通知");
			code = "1303";
			business = "callEnd";
			detailType = (short) ICommonConstants.CALLDETAILTYPE.CALLEND
					.ordinal();
		} else if (type.equals("callLost")) {
			logger.debug("未接通：通话繁忙");
			code = "1304";
			business = "callLost";
			detailType = (short) ICommonConstants.CALLDETAILTYPE.CALLFAILURE
					.ordinal();
		} else if (type.equals("callDialing")) {
			logger.debug("拨号中事件通知");
			code = "1305";
			business = "callDialing";
			detailType = (short) ICommonConstants.CALLDETAILTYPE.CALLDIALING
					.ordinal();
		} else if (type.equals("callFailure")) {
			logger.debug("通话失败事件通知");
			code = "1306";
			business = "callFailure";
			detailType = (short) ICommonConstants.CALLDETAILTYPE.CALLFAILURE
					.ordinal();
		} else {
			logger.debug("call 事件失效通知，type：" + type);
		}

		// 设置电话事件提醒消息
		Message message = new Message();
		message.setFromUser(commonService.getSystemUser());// 系统用户
		message.setType((short) ICommonConstants.MESSAGETYPE.CALL.ordinal());
		message.setDetailType(detailType);
		message.setToUser(agent);
		message.setCode(code);
		message.setBusiness(business);
		message.setHasRead((short) ICommonConstants.HASREAD.FALSE.ordinal());
		// 设置content
		Map<String, String> msgMap = new HashMap<String, String>();
		msgMap.put("taskId", task.getId().toString());
		if (call.getDirection() == ICommonConstants.DIRECTION.CALLIN.ordinal()) {
			msgMap.put("targetNumber", call.getCallingNumber());
			msgMap.put("myNumber", call.getCalledNumber());
		} else {
			msgMap.put("targetNumber", call.getCalledNumber());
			msgMap.put("myNumber", call.getCallingNumber());
		}
		msgMap.put("customerId", call.getCustomer().getId().toString());
		msgMap.put("customerName", call.getCustomer().getName());
		msgMap.put("callId", call.getId().toString());
		message.setContent(CommonUtil.mapToJsonString(msgMap));

		dslJpaService.setEntityClass(Message.class);
		message = (Message) dslJpaService.create(message);
		sendMessage(message);
		logger.debug("电话事件提醒");
	}

	/**
	 * 发送用户审核提醒
	 */
	public void userRemind(User user) {
		logger.debug("进入用户审核提醒方法");
		long userID = user.getId();
		user = this.em.find(User.class, userID);

		String code = "1203"; // 协议号
		String business = ""; // 业务编码
		Short detailType = (short) ICommonConstants.REMINDDETAILTYPE.USERRECORE
				.ordinal(); // 提醒详细类型

		Message message = new Message();
		message.setFromUser(commonService.getSystemUser());// 系统
		message.setType((short) ICommonConstants.MESSAGETYPE.REMIND.ordinal());
		message.setDetailType(detailType);
		message.setToUser(user);
		message.setCode(code);
		message.setHasRead((short) 0);
		// 设置content debugTest
		Map<String, String> msgMap = new HashMap<String, String>();
		msgMap.put("userId", user.getId().toString());
		msgMap.put("loginName", user.getLoginName());
		msgMap.put("status", ICommonConstants.IDCERTIFICATION.values()[user
				.getStatus()].label());
		Short statusSh = (short) ICommonConstants.IDCERTIFICATION.CERTIFYFAILURE
				.ordinal(); // 身份认证失败
		String status = user.getStatus().toString();
		if (status.equals(statusSh.toString())) {
			logger.debug("身份认证失败");
			msgMap.put("verifyFailReason", user.getVerifyFailReason());
			business = "userExamineFail";
		} else {
			business = "userExamineSuce";
		}
		message.setBusiness(business);
		message.setContent(CommonUtil.mapToJsonString(msgMap));
		dslJpaService.setEntityClass(Message.class);
		message = (Message) dslJpaService.create(message);
		sendMessage(message);
		logger.debug("开始发送用户审核提醒");

	}

	/**
	 * 发送企业任务审核提醒
	 */
	public void companyTaskRemind(Task task) {
		logger.debug("进入企业任务任何提醒方法");
		long taskId = task.getId();
		task = this.em.find(Task.class, taskId);

		String code = "1201"; // 协议号
		String business = task.getStatus().getTypecode(); // 业务编码
		Short detailType = (short) ICommonConstants.REMINDDETAILTYPE.TASKREMIND
				.ordinal();
		; // 提醒详细类型
		User user = this.em.find(User.class, task.getPubuser().getId());
		Message message = new Message();
		message.setFromUser(commonService.getSystemUser());// 系统
		message.setType((short) ICommonConstants.MESSAGETYPE.REMIND.ordinal());
		message.setDetailType(detailType);
		message.setToUser(user);
		message.setCode(code);
		if (business.equals("3")) {
			message.setBusiness("userExamineSuce");
		} else if (business.equals("4")) {
			message.setBusiness("userExamineFail");
		}
		message.setHasRead((short) 0);
		// 设置content debugTest
		Map<String, String> msgMap = new HashMap<String, String>();
		msgMap.put("userId", task.getPubuser().getId().toString());
		msgMap.put("taskId", Long.toString(taskId));
		msgMap.put("taskTitle", task.getTitle());
		msgMap.put("status", task.getStatus().getTypename());
		if (business.equals("taskNoPass")) {
			logger.debug("审核未通过");
			msgMap.put("verifyFailReason", task.getVerifyFailReason());
		}
		message.setContent(CommonUtil.mapToJsonString(msgMap));
		dslJpaService.setEntityClass(Message.class);
		message = (Message) dslJpaService.create(message);
		sendMessage(message);
		logger.debug("开始发送企业任务审核提醒");

	}

	/**
	 * 发送支付记录提醒
	 */
	public void parRecord(DealFlow dealFlow) {
		logger.debug("进入支付记录提醒方法");

		Long businessTypeId = dealFlow.getBusinessType().getId();
		Dicttype businessType = this.em.find(Dicttype.class, businessTypeId);

		String code = "1204"; // 协议号
		String business = businessType.getTypecode(); // 业务编码
		Short detailType = (short) ICommonConstants.REMINDDETAILTYPE.PAYRECORE
				.ordinal();
		; // 提醒详细类型
		User user = new User();
		Double amount = 0.0;// 金额
		Double Balance = 0.0;// 余额
		String failReason = "";// 客服提现失败原因
		String remark = "";// 充值备注
		if (business.equals("bizTypeWithdrawCash")) {
			logger.debug("客服提现成功通知");
			user = this.em.find(User.class, dealFlow.getPayer().getId());
			amount = dealFlow.getPayRecord().getAmount();
			Balance = dealFlow.getPayerBalance();
		} else if (business.equals("bizTypeWithdrawCashFailure")) {
			logger.debug("客服提现失败通知");
			user = this.em.find(User.class, dealFlow.getPayee().getId());
			amount = dealFlow.getAmount();
			Balance = dealFlow.getPayeeBalance();
			failReason = dealFlow.getPayRecord().getFailReason();
		} else if (business.equals("bizTypeRecharge")) {
			logger.debug("客户充值通知");
			user = this.em.find(User.class, dealFlow.getPayee().getId());
			amount = dealFlow.getAmount();
			Balance = dealFlow.getPayeeBalance();
			PayRecord payRecord = dealFlow.getPayRecord();
			if (payRecord == null) {
				remark = dealFlow.getRemark();
			}
		}

		Message message = new Message();
		message.setFromUser(commonService.getSystemUser());// 系统
		message.setType((short) ICommonConstants.MESSAGETYPE.REMIND.ordinal());
		message.setDetailType(detailType);
		message.setToUser(user);
		message.setCode(code);
		message.setBusiness(business);
		message.setHasRead((short) 0);
		// 设置content debugTest
		Map<String, String> msgMap = new HashMap<String, String>();
		msgMap.put("dealFlowId", dealFlow.getId().toString());
		msgMap.put("userId", user.getId().toString());
		msgMap.put("businessTypeName", businessType.getTypename());
		msgMap.put("tradeTime",
				CommonUtil.integetTimeForString(dealFlow.getTradeTime()));
		msgMap.put("amount", amount.toString());
		msgMap.put("Balance", Balance.toString());
		msgMap.put("failReason", failReason);
		msgMap.put("remark", remark);
		message.setContent(CommonUtil.mapToJsonString(msgMap));
		dslJpaService.setEntityClass(Message.class);
		message = (Message) dslJpaService.create(message);
		sendMessage(message);
		logger.debug("开始支付记录提醒");

	}

	/**
	 * 发送充值状态提醒
	 */
	public void rechargeRemind(PayRecord payRecord) {
		logger.debug("进入充值状态提醒");

		String code = "1204"; // 协议号
		String business = ""; // 业务编码
		Short detailType = (short) ICommonConstants.REMINDDETAILTYPE.PAYRECORE
				.ordinal();
		; // 提醒详细类型
		User user = payRecord.getUser();
		Double amount = payRecord.getAmount();// 金额
		String failReason = "";// 失败原因
		String remark = payRecord.getRemark();// 充值备注

		if (payRecord.getPayStatus() == ICommonConstants.PAYSTATUS.SUCC
				.ordinal()) {
			business = "rechargeSucc";
			logger.debug("充值成功提醒");
		} else if (payRecord.getPayStatus() == ICommonConstants.PAYSTATUS.FAIL
				.ordinal()) {
			business = "rechargeFail";
			failReason = "微信接口调用失败";
			logger.debug("充值失败提醒");
		}

		Message message = new Message();
		message.setFromUser(commonService.getSystemUser());// 系统
		message.setType((short) ICommonConstants.MESSAGETYPE.REMIND.ordinal());
		message.setDetailType(detailType);
		message.setToUser(user);
		message.setCode(code);
		message.setBusiness(business);
		message.setHasRead((short) ICommonConstants.HASREAD.FALSE.ordinal());
		// 设置content debugTest
		Map<String, String> msgMap = new HashMap<String, String>();
		msgMap.put("payRecordId", payRecord.getId().toString());
		msgMap.put("userId", user.getId().toString());
		msgMap.put("businessTypeName", business);
		msgMap.put("amount", amount.toString());
		msgMap.put("failReason", failReason);
		msgMap.put("remark", remark);
		message.setContent(CommonUtil.mapToJsonString(msgMap));
		dslJpaService.setEntityClass(Message.class);
		message = (Message) dslJpaService.create(message);
		sendMessage(message);
		logger.debug("开始充值状态提醒");

	}

	/**
	 * 发送微信绑定提醒
	 */
	public void wechatBindRemind(Wechat wechat) {
		logger.debug("进入微信绑定提醒");

		String code = "1205"; // 协议号
		String business = ""; // 业务编码
		Short detailType = (short) ICommonConstants.REMINDDETAILTYPE.WECHATBIND
				.ordinal(); // 提醒详细类型
		User user = wechat.getUser();
		String failReason = "";// 失败原因

		if (wechat.getBindStatus() == ICommonConstants.BINDSTATUS.TRUE
				.ordinal()) {
			business = "bindWechatSucc";
			logger.debug("微信绑定成功");
		} else if (wechat.getBindStatus() == ICommonConstants.BINDSTATUS.FALSE
				.ordinal()) {
			business = "rechargeFail";
			failReason = "微信接口调用失败";
			logger.debug("微信绑定失败");
		}

		Message message = new Message();
		message.setFromUser(commonService.getSystemUser());// 系统
		message.setType((short) ICommonConstants.MESSAGETYPE.REMIND.ordinal());
		message.setDetailType(detailType);
		message.setToUser(user);
		message.setCode(code);
		message.setBusiness(business);
		message.setHasRead((short) ICommonConstants.HASREAD.FALSE.ordinal());
		// 设置content debugTest
		Map<String, String> msgMap = new HashMap<String, String>();
		msgMap.put("userId", user.getId().toString());
		msgMap.put("businessTypeName", business);
		msgMap.put("failReason", failReason);
		message.setContent(CommonUtil.mapToJsonString(msgMap));
		dslJpaService.setEntityClass(Message.class);
		message = (Message) dslJpaService.create(message);
		sendMessage(message);
		logger.debug("开始微信绑定提醒");

	}

	/**
	 * 发送工单提醒
	 */
	public void workorderRemind(Workorder workorder, int thawType) {
		logger.debug("进入工单提醒方法");
		long workorderID = workorder.getId();
		workorder = this.em.find(Workorder.class, workorderID);

		String code = "1206"; // 协议号
		String business = ""; // 业务编码
		Short detailType = (short) ICommonConstants.REMINDDETAILTYPE.WORKORDER
				.ordinal(); // 提醒详细类型
		User user = new User();
		Message message = new Message();
		message.setFromUser(commonService.getSystemUser());// 系统
		message.setType((short) ICommonConstants.MESSAGETYPE.REMIND.ordinal());
		message.setDetailType(detailType);
		message.setCode(code);
		message.setHasRead((short) 0);
		// 设置content debugTest
		Map<String, String> msgMap = new HashMap<String, String>();
		msgMap.put("isSuccess",
				ICommonConstants.WORKORDERSTATUS.values()[workorder
						.getIsSuccess()].label());
		Short isSuccess = workorder.getIsSuccess();
		if (isSuccess == ICommonConstants.WORKORDERSTATUS.NOT.ordinal()) {// 未成单
			logger.debug("未成单");
			business = "workorderNot";
		} else if (isSuccess == ICommonConstants.WORKORDERSTATUS.APPLY
				.ordinal()) {// 待确认
			logger.debug("待确认");
			business = "workorderApply";
			user = workorder.getTask().getPubuser();
		} else if (isSuccess == ICommonConstants.WORKORDERSTATUS.CONFIRM
				.ordinal()) {// 确认成单
			logger.debug("确认成单");
			business = "workorderConfirm";
			user = workorder.getCreater();
		} else if (isSuccess == ICommonConstants.WORKORDERSTATUS.FROZEN
				.ordinal()) {// 已冻结
			logger.debug("已冻结");
			business = "workorderFrozen";
			user = workorder.getCreater();
		}
		msgMap.put("userId", user.getId().toString());
		msgMap.put("title", workorder.getTitle());
		msgMap.put("taskName", workorder.getTask().getTitle());
		message.setToUser(user);
		message.setBusiness(business);
		message.setContent(CommonUtil.mapToJsonString(msgMap));
		dslJpaService.setEntityClass(Message.class);
		// 解冻方式：0企业解冻 1运营解冻
		if (thawType == ICommonConstants.THAWTYPE.COM.ordinal()) {// 企业解冻,发送给客服
			user = workorder.getCreater();
			message.setToUser(user);
			business = "workorderThaw";
			message.setBusiness(business);
		} else if (thawType == ICommonConstants.THAWTYPE.BACK.ordinal()) {// 运营解冻，发送给企业和客服
			business = "workorderApply";

			Message msg = new Message();
			msg.setFromUser(commonService.getSystemUser());// 系统
			msg.setType((short) ICommonConstants.MESSAGETYPE.REMIND.ordinal());
			msg.setDetailType(detailType);
			msg.setCode(code);
			msg.setHasRead((short) 0);
			msg.setToUser(user);
			msg.setBusiness(business);
			msg.setContent(CommonUtil.mapToJsonString(msgMap));
			business = "workorderThaw";
			msg.setBusiness(business);
			user = workorder.getTask().getPubuser();
			msg.setToUser(user);
			dslJpaService.setEntityClass(Message.class);
			msg = (Message) dslJpaService.create(msg);
			sendMessage(msg);

			user = workorder.getCreater();
			message.setBusiness(business);
			message.setToUser(user);
		}
		dslJpaService.setEntityClass(Message.class);
		message = (Message) dslJpaService.create(message);
		sendMessage(message);
		logger.debug("开始发送工单提醒");
	}

	/**
	 * 获取
	 */
	public List getLatestMessage() {
		Map<Short, Message> messageMap = new HashMap<>();
		List dataListTemp = new ArrayList<>();
		List dataList = new ArrayList<>();
		// 获取时间最近的消息
		StringBuilder sql = new StringBuilder(
				"select a.* from tnb_message a "
						+ "inner join (select detail_type,max(create_time) create_time from tnb_message group by detail_type)b "
						+ "on a.detail_type=b.detail_type and a.create_time=b.create_time where a.del_status!=1 order by a.detail_type");

		dataListTemp = getJdbcTemplate().queryForList(sql.toString());
		Iterator it = dataListTemp.iterator();
		while (it.hasNext()) {
			Map rece = (Map) it.next();
			System.out.println(rece.get("tenant_id") + "---" + rece.get("id")
					+ "---" + rece.get("detail_type") + "---"
					+ rece.get("create_time") + "---" + rece.get("content"));
			Message temp = new Message();
			Tenant tenant = new Tenant();
			tenant.setId(Long.parseLong(rece.get("tenant_id").toString()));
			temp.setDetailType(Short.parseShort(rece.get("detail_type")
					.toString()));
			temp.setCreateTime(Integer.parseInt(rece.get("create_time")
					.toString()));
			temp.setContent(rece.get("content").toString());
			temp.setBusiness(rece.get("business").toString());
			temp.setId(Long.parseLong(rece.get("id").toString()));// 可能存在重复
			messageMap.put(temp.getDetailType(), temp);
			System.out.println(temp.getDetailType() + " " + messageMap.size()
					+ " " + messageMap.get(temp.getDetailType()).getContent());
		}
		// 获取每类消息未读数目 将相应数目set消息 num
		StringBuilder sql2 = new StringBuilder(
				"select detail_type type,count(*) num from tnb_message where del_status!=1 and has_read=0 group by detail_type");
		dataListTemp.clear();
		dataListTemp = getJdbcTemplate().queryForList(sql2.toString());
		it = dataListTemp.iterator();
		while (it.hasNext()) {
			Map rece = (Map) it.next();
			System.out.println(rece.get("tenant_id") + "---" + rece.get("id")
					+ "---" + rece.get("detail_type") + "---"
					+ rece.get("create_time") + "---" + rece.get("content"));
			if (messageMap.containsKey(Short.parseShort(rece.get("type")
					.toString()))) {
				messageMap.get(Short.parseShort(rece.get("type").toString()))
						.setNum(Integer.parseInt(rece.get("num").toString()));
			}
		}
		it = messageMap.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			Message val = (Message) entry.getValue();
			dataList.add(val);
		}
		return dataList;
	}

	/**
	 * 发送预警提醒
	 */
	public void warningRemind(HbeaconWarning warning, String type) {
		logger.debug("进入预警提醒方法");
		Message message = new Message();
		Customer customer = warning.getCaller();
		List<User> users = userService.getAllUserList(customer.getTenant());// 本机构所有人
		if (users != null && users.size() > 0) {
			Short detailType = null;
			if ("".equals(type) || type == null) {
				detailType = (short) ICommonConstants.REMINDDETAILTYPE.HBEACONCALL
						.ordinal(); // 按键提醒详细类型11
				message.setBusiness("buttonCalling");
			}
			if ("warn".equals(type)) {// 床垫 心率骤降
				detailType = (short) ICommonConstants.REMINDDETAILTYPE.HEARTRATECALL
						.ordinal(); // 提醒详细类型10
				if (warning.getReason() != null
						&& warning.getReason().contains("心率")) {
					message.setBusiness("xinlv");
				}
				if (warning.getReason() != null
						&& warning.getReason().contains("呼吸")) {
					message.setBusiness("huxi");
				}
			}
			if ("mattressStatus".equals(type)) {// 离床
				detailType = (short) ICommonConstants.REMINDDETAILTYPE.LEAVEBEDCALL
						.ordinal(); // 提醒详细类型9
				if (warning.getReason() != null
						&& warning.getReason().contains("离")) {
					message.setBusiness("lichuang");
				}
				if (warning.getReason() != null
						&& warning.getReason().contains("回")) {
					message.setBusiness("huichuang");
				}
			}
			Bed bed = workPlaceService.getBed(customer.getBed());
			message.setType(new Integer(
					CommonConstants.MESSAGE.MESSAGETYPE_NOTICE.label())
					.shortValue());
			message.setCode(CommonConstants.MESSAGE.MESSAGECODE_CALLINGNOTICE
					.label());
			message.setCreateTime(CommonUtil.getCurrTimes());
			message.setType((short) ICommonConstants.MESSAGETYPE.REMIND
					.ordinal());
			message.setDetailType(detailType);
			message.setTenant(customer.getTenant());
			message.setCreateTime(CommonUtil.getCurrTimes());
			// 设置content debugTest
			Map<String, String> msgMap = new HashMap<String, String>();
			// message.setToUser(user);
			// 设置消息内容
			msgMap.put("createTime", String.valueOf(CommonUtil.getCurrTimes()));
			if (customer != null) {
				msgMap.put("customerId", customer.getId().toString());
				msgMap.put("customerName", customer.getName());
			}
			msgMap.put("bedId", warning.getBed().getId().toString());
			msgMap.put("location", bed.getRoom().getFloor().getBuilding()
					.getName()
					+ "-"
					+ bed.getRoom().getFloor().getName()
					+ "-"
					+ bed.getRoom().getName());
			// msgMap.put("bedName", bed.getName());
			msgMap.put("content", warning.getReason());
			message.setContent(CommonUtil.mapToJsonString(msgMap));
			// 使用类型作为通知的业务类型
			message.setHasRead(new Integer(0).shortValue());
			// 取得需要发送的用户--发送给所有本机构的人员
			message.setUserList(users);
			dslJpaService.setEntityClass(Message.class);
			message = (Message) dslJpaService.create(message);
			ActionContextHolder.getMessageQueue().addWarningMsg(message);
		}
		// sendMessage(message);
		logger.debug("开始预警提醒");
	}

	/**
	 * 发送位置提醒
	 */
	public void locationRemind(PersonLocation location) {
		logger.debug("进入位置提醒方法");
		Message message = new Message();
		Customer customer = location.getCustomer();
		List<User> users = userService.getAllUserList(customer.getTenant());// 本机构所有人
		if (users != null && users.size() > 0) {
			Short detailType = (short) ICommonConstants.REMINDDETAILTYPE.LOCATIONINFO
					.ordinal(); // 提醒详细类型
			message.setType(new Integer(
					CommonConstants.MESSAGE.MESSAGETYPE_NOTICE.label())
					.shortValue());
			message.setCode(CommonConstants.MESSAGE.MESSAGECODE_LOCATIONNOTICE
					.label());
			message.setCreateTime(CommonUtil.getCurrTimes());
			message.setType((short) ICommonConstants.MESSAGETYPE.REMIND
					.ordinal());
			message.setDetailType(detailType);
			message.setTenant(customer.getTenant());
			message.setCreateTime(CommonUtil.getCurrTimes());
			// 设置content debugTest
			Map<String, String> msgMap = new HashMap<String, String>();
			// message.setToUser(user);
			// 设置消息内容
			msgMap.put("createTime", String.valueOf(CommonUtil.getCurrTimes()));
			if (customer != null) {
				msgMap.put("customerId", customer.getId().toString());
				msgMap.put("customerName", customer.getName());
			}
			msgMap.put("roomId", location.getRoom().getId().toString());
			msgMap.put("type", "1");
			msgMap.put("location", location.getRoom().getFloor().getBuilding()
					.getName()
					+ "-"
					+ location.getRoom().getFloor().getName()
					+ "-"
					+ location.getRoom().getName());
			// msgMap.put("bedName", bed.getName());
			msgMap.put("content", "位置提醒");
			message.setContent(CommonUtil.mapToJsonString(msgMap));
			// 使用类型作为通知的业务类型
			message.setBusiness("hbeaconlocation");
			message.setHasRead(new Integer(0).shortValue());
			// 取得需要发送的用户--发送给所有本机构的人员
			message.setUserList(users);
			dslJpaService.setEntityClass(Message.class);
			message = (Message) dslJpaService.create(message);
			ActionContextHolder.getMessageQueue().addWarningMsg(message);
		}
		// sendMessage(message);
		logger.debug("开始位置提醒");
	}

	/**
	 * webSocket关闭之后的相关操作
	 *
	 * @author ytche
	 * @param session
	 * @date 2017年8月29日 上午11:17:03
	 */
	public void closeSession(WebSocketSession session) {
		if (session == null) {
			return;
		}
		Map<String, UserSession> evaHolder = ActionContextHolder.getEvaHolder();
		for (Entry<String, UserSession> entry : evaHolder.entrySet()) {
			if (entry.getValue() != null
					&& entry.getValue().getWebSocketSession() != null
					&& entry.getValue().getWebSocketSession().getId()
							.equals(session.getId())) {
				entry.getValue().setWebSocketSession(null);
			}
		}
	}
}
